package com.vimi8.ebb.auth.configuration;

import com.vimi8.ebb.auth.model.ClientUser;
import com.vimi8.ebb.auth.service.UserAuthorityService;
import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.OAuth2Authentication;

import java.security.KeyPair;
import java.util.*;

/**
 * Created by xuybin on 2016/9/9.
 */
public class JwtAccessTokenConverterImpl extends BaseJwtAccessTokenConverterImpl {
    private UserAuthorityService userAuthorityService;

    public  JwtAccessTokenConverterImpl(String resourceId,UserAuthorityService userAuthorityService,KeyPair keyPair){
        super(resourceId);
        this.userAuthorityService=userAuthorityService;
        setKeyPair(keyPair);
    }

    @Override
    public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {
        final Map<String, Object> decodedDetails = new HashMap<>();

        String clienId=authentication.getOAuth2Request().getClientId();
        String loginName=authentication.getName();
        String openId=null;
        ClientUser clientUser=null;
        try {
            clientUser= userAuthorityService.getClientUserByLoginNameAndClientId(loginName,clienId);
        }catch (Exception ex){
            logger.error(ex.getLocalizedMessage());
        }
        if(clientUser!=null){
            //附加用户openid
            openId=clientUser.getOpenid();
            decodedDetails.put(OPENID, clientUser.getOpenid());
            //附加job
            decodedDetails.put(JOB, clientUser.getJob());
            decodedDetails.put(CLIENTORGCLASS, clientUser.getClientOrgClass());
            ((DefaultOAuth2AccessToken)accessToken).setAdditionalInformation(decodedDetails);
            //附加用户的权限范围,以替换clienId的权限范围(用户登陆且存在自己权限时，只能使用用户自己的权限)
            Set<String> scopeSet=new LinkedHashSet<>();
            scopeSet.addAll(Arrays.asList(clientUser.getScopes().split("\\|")));
            ((DefaultOAuth2AccessToken)accessToken).setScope(scopeSet);

            //附加用用户能访问的资源,以替换clienId的资源
            authentication.getOAuth2Request().getResourceIds().clear();
            //测试是否生效authentication.getOAuth2Request().getResourceIds().add("xyb-123");
            authentication.getOAuth2Request().getResourceIds().addAll(Arrays.asList(clientUser.getResources().split("\\|")));
            //跟新最后登录时间

            userAuthorityService.updateLastLoginTime(clienId,openId);
        }
        return super.enhance(accessToken, authentication);

    }
}
